﻿using MassTransit;
using SagaOrders.Application.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SagaOrders.Application.StateMachine
{
    public class OrderStateMachine:MassTransitStateMachine<OrderState>
    {
        public State Pending { get; set; }
        public State Paid { get; set; }
        public State Cancelled { get; set; }

        public Event<OrderCreated> OrderCreated { get; private set; }
        public Event<PayOrder> PayOrder { get; private set; }
        public Event<CancelOrder> CancelOrder { get; private set; }

        public OrderStateMachine()
        {
            InstanceState(x => x.CurrentState);
            Event(() => OrderCreated, x => x.CorrelateById(context => context.Message.OrderId));
            Event(() => PayOrder, x => x.CorrelateById(context => context.Message.OrderId));
            Event(() => CancelOrder, x => x.CorrelateById(context => context.Message.OrderId));

            Initially(When(OrderCreated)
                .Then(context => 
                {
                    context.Saga.OrderId=context.Message.OrderId;
                    context.Saga.Amount=context.Message.Amount;
                    context.Saga.CreatedAt=context.Message.CreatedAt;
                    Console.WriteLine($"Order was created:{context.Message.OrderId}");
                }).TransitionTo(Pending));

            During(Pending, When(PayOrder)
                .Then(context => {
                    context.Saga.Amount=context.Message.Amount;
                    context.Saga.PaidAt=DateTime.UtcNow;
                    Console.WriteLine($"Paid the order with ID:{context.Message.OrderId}");
                }).TransitionTo(Paid)
                .Publish(context => new OrderPaid{ 
                    OrderId = context.Saga.OrderId,
                }),
                When(CancelOrder)
                .Then(context => {
                    context.Saga.CancelledAt=DateTime.UtcNow;
                    Console.WriteLine($"Order cancelled:{context.Message.OrderId}");
                }).TransitionTo(Cancelled)
                .Publish(context=>new OrderCancelled() 
                {
                    OrderId= context.Saga.OrderId,
                })
                );
        }
    }
}
